package com.demo.juc.state;

import java.util.concurrent.TimeUnit;

/**
 * BlockedThread主要是在synchronized代码块中的while(true)循环中调用TimeUnit.SECONDS.sleep(long)方法来验证线程的
 * BLOCKED状态。
 * <p>
 * 当启动两个BlockedThread线程时，首先启动的线程会处于TIMED_WAITING状态，后启动的线程会处于
 * BLOCKED状态。
 *
 * "BlockedThread_01" #14 prio=5 os_prio=0 tid=0x000000001f4f3800 nid=0x4d80 waiting on condition [0x000000002047f000]
 *    java.lang.Thread.State: TIMED_WAITING (sleeping)
 *
 *  "BlockedThread_02" #15 prio=5 os_prio=0 tid=0x000000001f4f4800 nid=0x4ad8 waiting for monitor entry [0x000000002057e000]
 *    java.lang.Thread.State: BLOCKED (on object monitor)
 */
public class BlockedThread implements Runnable {
    @Override
    public void run() {
        while (true) {
            synchronized (BlockedThread.class) {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
